package com.lwj.project1;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.ContentUris;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.lwj.project1.databaseHelper.ImageUtil;
import com.lwj.project1.databaseHelper.MySqliteOpenHelper;
import com.lwj.project1.entity.User;
import com.lwj.project1.myToast.MyToast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class RegisterActivity extends AppCompatActivity {
    private EditText editUsername;
    private EditText editPassword;
    private EditText editPhone;
    private EditText editEmail;
    private CheckBox protocol;
    private RadioGroup sex;
    private ImageButton registerButton;
    private ImageButton head;
    private String headStr;
    private TextView name_notice;
    private TextView password_notice;
    private TextView email_notice;
    private TextView phone_notice;
    MyToast myToast;
    private String username,password,email,phone;
    private final String emailREGEX = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";
    String sexChecked;
    private final MySqliteOpenHelper mySqliteOpenHelper = new MySqliteOpenHelper(RegisterActivity.this);


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        myToast = new MyToast(getApplicationContext());
        editUsername = findViewById(R.id.register_username);
        editPassword = findViewById(R.id.register_password);
        editPhone = findViewById(R.id.register_phone);
        editEmail = findViewById(R.id.register_email);
        protocol = findViewById(R.id.protocol);
        sex = findViewById(R.id.sex);
        registerButton = findViewById(R.id.register_button);
        head = findViewById(R.id.head);
        name_notice = findViewById(R.id.register_username_notice);
        password_notice = findViewById(R.id.register_password_notice);
        email_notice = findViewById(R.id.register_email_notice);
        phone_notice = findViewById(R.id.register_phone_notice);

        registerButton.setOnClickListener(v -> {
            if (!protocol.isChecked()){
                myToast.showToastWithImg("请先勾选用户协议哦~",getDrawable(R.drawable.toast_img));
                return;
            }
            if (editUsername.getText() == null) {
                name_notice.setText("*用户名可不能为空哦~");
                return;
            }
            if(mySqliteOpenHelper.findUserByName(editUsername.getText().toString()) != null){
                name_notice.setText("*该名称已经有用户使用了哦，请换一个吧~");
                return;
            }
            if (editPassword.getText() == null) {
                password_notice.setText("*密码可不能为空呢~");
                return;
            }
            if (editEmail.getText() == null) {
                email_notice.setText("*邮箱也不可以为空哦~");
                return;
            }
            if (mySqliteOpenHelper.findUserByEmail(editEmail.getText().toString()) != null){
                email_notice.setText("*该邮箱已经被用户注册了哦~");
                return;
            }
            if (editPhone.getText() == null) {
                phone_notice.setText("*电话号码也要记得填~");
                return;
            }
            User user = new User(0,editUsername.getText().toString(),headStr,editPhone.getText().toString(),editPassword.getText().toString(),editEmail.getText().toString(),sexChecked,"您暂时还没有自我介绍哦，快来介绍一下自己吧~");
            if (mySqliteOpenHelper.addUser(user)){
                SharedPreferences sharedPreferences = getSharedPreferences("project_content",MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString("username",editUsername.getText().toString());
                editor.putString("password",editPassword.getText().toString());
                editor.apply();
            } else {
                myToast.showToastWithImg("该用户已经注册过啦~",getDrawable(R.drawable.toast_img));
                return ;
            }
            myToast.showToastWithImg("注册成功啦~",getDrawable(R.drawable.toast_img));
            Intent intent = new Intent(RegisterActivity.this,LoginActivity.class);
            startActivity(intent);
        });
        head.setOnClickListener(v -> {
            if (ContextCompat.checkSelfPermission(RegisterActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED){
                getFromAlbum();
            }else{
                ActivityCompat.requestPermissions(RegisterActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},0);
            }
        });
        sex.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId){
                case R.id.sex_man:
                    sexChecked = "男";
                    break;
                case R.id.sex_woman:
                    sexChecked = "女";
                    break;
                case R.id.sex_secret:
                    sexChecked = "秘";
                    break;
            }
        });
        editUsername.setOnFocusChangeListener((v, hasFocus) -> {
            username = editUsername.getText().toString();
            if (hasFocus){
                name_notice.setText("");
            }
            else{
                if (username.length() < 6){
                    name_notice.setText("*用户名不可以小于6位哦~");
                }
            }
        });
        editPassword.setOnFocusChangeListener((v, hasFocus) -> {
            password = editPassword.getText().toString();
            if (hasFocus){
                password_notice.setText("");
            }
            else{
                if (password.length() < 6){
                    password_notice.setText("*密码不可以少于8位哦~");
                }
            }
        });
        editEmail.setOnFocusChangeListener((v, hasFocus) -> {
            email = editEmail.getText().toString();
            if (hasFocus){
                email_notice.setText("");
            }
            else{
                if (!email.matches(emailREGEX)){
                    email_notice.setText("*email格式不正确哦~");
                }
            }
        });
        editPhone.setOnFocusChangeListener((v, hasFocus) -> {
            phone = editPhone.getText().toString();
            if (hasFocus){
                phone_notice.setText("");
            }
            else{
                if (phone.length() != 11){
                    phone_notice.setText("*电话号码格式不正确哦~");
                }
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @NonNull Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1){
            handleImage(data);
        }
    }

    private String getImagePath(Uri uri,String selection){
        String path = null;
        Cursor cursor = getContentResolver().query(uri,null,selection,null,null);
        if (cursor != null){
            if (cursor.moveToFirst()){
                path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    private void handleImage(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(RegisterActivity.this,uri)){
            String documentId = DocumentsContract.getDocumentId(uri);
            if (TextUtils.equals(uri.getAuthority(),"com.android.providers.media.documents")){
                String id = documentId.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection);
            }else if (TextUtils.equals(uri.getAuthority(),"com.android.providers.downloads.documents")){
                if (documentId != null && documentId.startsWith("msf:")){
                    resolveMSF(uri,documentId);
                    return;
                }
                Uri contentUri =  ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),Long.valueOf(documentId));
                imagePath = getImagePath(contentUri,null);
            }
        }else if ("content".equalsIgnoreCase(uri.getScheme())){
            imagePath = getImagePath(uri,null);
        }else if ("file".equalsIgnoreCase(uri.getScheme())){
            imagePath = uri.getPath();
        }
        if (imagePath != null){
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            head.setImageBitmap(bitmap);
            headStr = ImageUtil.imageToBase64(bitmap);
        }
    }

    private void resolveMSF(Uri uri, String documentId) {
        File file = new File(getCacheDir(),"temp_file" + getContentResolver().getType(uri).split("/")[1]);
        try {
            InputStream inputStream = getContentResolver().openInputStream(uri);

            OutputStream outputStream = new FileOutputStream(file);

            byte[] buffer = new byte[4*1024];
            int read;
            while ((read = inputStream.read(buffer)) != -1){
                outputStream.write(buffer,0,read);
            }
            outputStream.flush();

            Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
            head.setImageBitmap(bitmap);
            headStr = ImageUtil.imageToBase64(bitmap);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,@NonNull String[] permissions,@NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 0){
            if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                getFromAlbum();
            }else{
                myToast.showToastWithImg("访问相册权限被拒绝~",getDrawable(R.drawable.toast_img));
            }
        }

    }
    private void getFromAlbum() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent,1);
    }
}